<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">所授教师：</span>
      <el-select
        v-model="params.name"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur"
        @clear="selectClear"
        @change="selectChange"
      >
        <el-option
          v-for="(item, index) in teachers"
          :key="index"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <span class="search-label" style="margin-left: 10px">学期：</span>
      <el-select
        v-model="params.termName"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur2"
        @clear="selectClear2"
        @change="selectChange2"
      >
        <el-option
          v-for="(item, index) in terms"
          :key="index"
          :label="item.termName"
          :value="item.termName"
        />
      </el-select>
      <span class="search-label" style="margin-left: 10px">班级：</span>
      <el-select
        v-model="params.className"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur3"
        @clear="selectClear3"
        @change="selectChange3"
      >
        <el-option
          v-for="(item, index) in classs"
          :key="index"
          :label="item.className"
          :value="item.className"
        />
      </el-select>
      <el-button type="primary" class="search-btn" @click="search"
        >查询</el-button
      >
    </div>
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button @click="batchDelete">批量删除</el-button>
      <el-button @click="handleExportExcel">导出excel表</el-button>
      <el-button @click="createscore">生成成绩信息</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="100"
        />
        <el-table-column label="所授教师" prop="teacherName" />
        <el-table-column label="学期" prop="termName" />
        <el-table-column label="班级" prop="className" />
        <el-table-column label="课程名字" prop="courseName" />
        <el-table-column label="操作" fixed="right" width="90">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="
                edit(
                  scope.row.courseId,
                  scope.row.teacherName,
                  scope.row.termName,
                  scope.row.className,
                  scope.row.courseName
                )
              "
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="deleteOne(scope.row.courseId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加或修改操作日志记录对话框 -->
    <el-dialog :visible.sync="open" width="500px" append-to-body>
      <span slot="title">{{
        Form.courseId ? "修改课程信息" : "添加课程信息"
      }}</span>
      <el-form ref="form" :model="Form" :rules="Rules" label-width="80px">
        <el-form-item label="所授教师" prop="colleges">
          <el-select v-model="Form.teacherId">
            <el-option
              v-for="item in teachers"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="colleges">
          <el-select v-model="Form.termId">
            <el-option
              v-for="item in terms"
              :key="item.termId"
              :value="item.termId"
              :label="item.termName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="colleges">
          <el-select v-model="Form.classId">
            <el-option
              v-for="item in classs"
              :key="item.classId"
              :value="item.classId"
              :label="item.className"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名字" prop="courseName">
          <el-input v-model="Form.courseName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  getpageCourseTeacherAPI,
  addOrEditCourseAPI,
  deleteCourseAPI,
  exportExcel2API,
  generateScoreAPI,
} from "@/api/course";
import { getAllTeachersAPI } from "@/api/user";
import { getAllTermsAPI } from "@/api/term";
import { getAllClassesAPI } from "@/api/classes";

export default {
  name: "Check_results",
  data() {
    return {
      Rules: {
        courseName: [
          {
            required: true,
            message: "请输入课程名字",
            trigger: "blur",
          },
        ],
      },
      Form: {
        courseId: "",
        teacherId: "",
        termId: "",
        classId: "",
        courseName: "",
      },
      teachers: [],
      terms: [],
      classs: [],
      open: false,
      selecttionVal: [],
      total: 0, //页总数
      list: [], //列表
      params: {
        //参数
        page: 1,
        pageSize: 2,
        name: "",
        termName: "",
        className: "",
        courseName: "",
      },
    };
  },
  created() {
    this.getpageCourseTeacher();
    this.getAllTeachers();
    this.getAllTerms();
    this.getAllClasses();
  },
  methods: {
    async createscore() {
      await generateScoreAPI(this.params);
      this.$message.success("生成成绩成功")
    },
    handleExportExcel() {
      exportExcel2API(this.params)
        .then((response) => {
          const blob = new Blob([response], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });

          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = "scores.xlsx";
          link.click();

          window.URL.revokeObjectURL(link.href);
        })
        .catch((error) => {
          console.error("Failed to export Excel:", error);
        });
    },
    //多选框输入值
    selectBlur(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.name = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear() {
      this.params.name = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange(val) {
      this.params.name = val;
      this.$forceUpdate();
    },
    //多选框输入值
    selectBlur2(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.termName = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear2() {
      this.params.termName = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange2(val) {
      this.params.termName = val;
      this.$forceUpdate();
    },
    //多选框输入值
    selectBlur3(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.className = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear3() {
      this.params.className = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange3(val) {
      this.params.className = val;
      this.$forceUpdate();
    },
    //获取班级数据
    async getAllClasses() {
      const res = await getAllClassesAPI();
      this.classs = res.data;
    },
    //获取学期数据
    async getAllTerms() {
      const res = await getAllTermsAPI();
      this.terms = res.data;
    },
    //获取教师数据
    async getAllTeachers() {
      const res = await getAllTeachersAPI();
      this.teachers = res.data;
    },
    //单个删除
    deleteOne(id) {
      this.$confirm("您确定要删除此数据吗?", "提示")
        .then(async () => {
          // console.log('点击确定');
          await deleteCourseAPI(id);
          this.$message.success("删除成功");
          if (this.list.length == 1 && this.params.page > 1) {
            this.params.page--;
          }
          this.getAllMajors();
          this.getpageCourseTeacher();
        })
        .catch(() => {});
    },
    //批量删除
    batchDelete() {
      if (this.selecttionVal.length <= 0) {
        this.$message.warning("请先选择要删除的数据");
        return;
      }
      const ids = this.selecttionVal.map((item) => {
        return item.courseId;
      });
      this.$confirm("您确定要删除此数据吗?", "提示")
        .then(async () => {
          await deleteCourseAPI(ids.join(","));
          this.$message.success("批量删除成功");
          this.getAllMajors();
          if (
            this.list.length == this.selecttionVal.length &&
            this.params.page > 1
          ) {
            this.params.page--;
          }
          this.getpageCourseTeacher();
        })
        .catch(() => {});
    },
    //获取选择的数据
    handleSelectionChange(val) {
      this.selecttionVal = val;
    },
    //提交表格
    submitForm() {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return;
        if (this.Form.majorId != "") {
          //修改操作
          await addOrEditCourseAPI(this.Form);
          this.$message.success("修改成功");
          this.getAllMajors();
        } else {
          //新增操作
          await addOrEditCourseAPI(this.Form);
          this.$message.success("添加成功");
          this.getAllMajors();
          this.reset();
          this.params.page = 1;
        }
        this.open = false;
        this.getpageCourseTeacher();
      });
    },
    //编辑按钮
    async edit(courseId, teacherName, termName, className, courseName) {
      this.Form.courseId = courseId;
      //找到名称对应的Id
      const teacher = this.teachers.find((item) => item.name === teacherName);
      const term = this.terms.find((item) => item.termName === termName);
      const oneclass = this.classs.find((item) => item.className === className);
      this.Form.teacherId = teacher.id;
      this.Form.termId = term.termId;
      this.Form.classId = oneclass.classId;
      this.Form.courseName = courseName;
      this.open = true;
    },
    // 表单重置
    reset() {
      this.Form.teacherId = this.teachers[0].id;
      this.Form.termId = this.terms[0].termId;
      this.Form.classId = this.classs[0].classId;
      this.Form.courseName = "";
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.Form.teacherId = this.teachers[0].id;
      this.Form.termId = this.terms[0].termId;
      this.Form.classId = this.classs[0].classId;
      if (this.Form.courseId) {
        this.Form.courseId = "";
        this.Form.courseName = "";
      }
      this.open = true;
    },
    //获取专业分页数据
    async getpageCourseTeacher() {
      const res = await getpageCourseTeacherAPI(this.params);
      this.total = res.data.total;
      this.list = res.data.records;
    },
    //获取专业列表
    async getAllMajors() {
      const res = await getAllMajorsAPI();
      this.majors = res.data;
    },

    //点击查询按钮
    search() {
      this.params.page = 1;
      this.getpageCourseTeacher();
    },
    //计算序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1;
    },
    //页数改变
    handleCurrentChange(val) {
      this.params.page = val;
      this.getpageCourseTeacher();
    },
    //页条数改变
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getpageCourseTeacher();
    },
  },
};
</script>


<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>